<?php

namespace App\Repos;

use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\OrderGroup;
use App\Models\Product;
use App\Models\ProductSpec;
use App\Models\User;
use Carbon\Carbon;
use App\Services\WechatTpl;
use DB,Log;

class OrderGroupRepo 
{	
    public static function info($code)
    {
        $data['status'] = 50;
        
        

    	$ogWhere['group_code'] = $code;
    	$ogWhere['parent_id'] = 0;
    	$og = OrderGroup::where($ogWhere)->first();
        if(object_get($og,'status')==60) {
            $data['status'] = 60;
        }

    	$product = Product::find($og->product_id);    	
    	
    	$all = OrderGroup::where('product_id',$og->product_id)->count();
        $data['thumb'] = $product->thumb;
    	$data['needPersons'] = $product->group_num;
    	$data['totalPersons'] = $all;
    	$data['countdownTime'] = Carbon::now()->diffInSeconds($og->end_at);

    	$list = DB::table('order_groups as og')
        ->join('users as u','u.id','=','og.user_id')
        ->select(['og.id','u.nickname','u.avatar','og.created_at','og.group_code','og.end_at','og.parent_id'])
        ->where('og.group_code',$code)
        ->orderBy('og.id','asc')
        ->get();
        $data['groupMember'] = $list;
       
        return $data;
    }

    public static function userInfo($group_code)
    {
        $user_ids = OrderGroup::where(['group_code'=>$group_code])
                                ->pluck('user_id');
        $nicknames = User::whereIn('id',$user_ids)
                            ->pluck('nickname')
                            ->toArray(); 
        return implode(',', $nicknames);                                           
    }

    public static function groupFaild()
    {
        // 查询已到期的正在进行的拼团
        $time = date('Y-m-d H:i:s');
        $order_ids = OrderGroup::where('end_at','<',$time)
            ->where('status',50)
            ->pluck('order_id');
        $list = OrderGroup::whereIn('order_id',$order_ids)
            ->update(['status'=>'-50']);

        foreach ($order_ids as $order_id) {
            $order = Order::find($order_id);
            $order->status = '-50';
            $order->save();

            // 恢复库存
            $ops = OrderProduct::where(['order_id'=>$order_id])->get();
            foreach ($ops as $k => $op) {
                $pp = ProductSpec::find($op->spec_id);
                $pp->spec_num += $op->product_num;
                $pp->save();
            }
            
            


            if( $order->transaction_id && $order->total_price>29) {
                $money['money']   = $order->total_price;
                $money['remark']  = '拼团成功，超过24小时未接单订单自动订单退款';           
                $openid   = object_get($order,'user.small_openid');
                $flag     = WechatTpl::toBalance($money,$openid);
                Log::info('退款结果:'.json_encode($flag));
            }

            // 推送
            $msg = $order->toArray();
            $msg['total_money']  = $order->total_price/100;
            $msg['openid']       = object_get($order,'user.small_openid'); 
            $msg['shop_name']    = object_get($order,'shop.name');
            $msg['product_info'] = OrderRepo::productInfo($order->id);
            $msg['remark']       = '拼团人数不足，订单取消';
            Log::info('拼团人数不足，订单取消:'.json_encode($msg));
            WechatTpl::sendTplMsg('group_failed',$msg);
        }       

        return true;
    }

    public static function find($where)
    {
        return OrderGroup::where($where)->first();
    }

    public static function getListByGroupCode($group_code)
    {
        $list = DB::table('order_groups as og')
        ->join('users as u','u.id','=','og.user_id')
        ->join('orders as o','o.id','=','og.order_id')
        ->select('u.small_openid','u.nickname','og.group_code','o.prepay_id')
        ->where('og.group_code',$group_code)
        ->get();
        return $list;
    }
}
